package com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeCardiacDetection;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.example.anew.journey.mynewjourney.MyAnimationListener;
import com.example.anew.journey.mynewjourney.R;
import com.example.anew.journey.mynewjourney.base.FirstChangeAllBaseActivity;
import com.example.anew.journey.mynewjourney.customview.MyCardiacDetectionCustomView;
import com.example.anew.journey.mynewjourney.customview.RingView;
import com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeCardiacDetection.persenter.FirstChangeCardiacDetectionPersenter;
import com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeCardiacDetection.view.ISFirstChangeCardiacDetectionView;
import com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeDirectionsUse.FirstChangeDirectionsUseActvity;
import com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeHistoricalRecordDateList.FirstChangeHistoricalRecordDateListActivity;
import com.example.anew.journey.mynewjourney.firstchangelogic.frstChangeSecondTimeCardiacDetection.FrstChangeSecondTimeCardiacDetectionActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.jesse.nativelogger.NLogger;

/**
 * 杭州惟君医疗科技有限公司11
 * Created by 20433 on 2018/3/19
 */

public class FirstChangeCardiacDetectionActivity extends FirstChangeAllBaseActivity implements ISFirstChangeCardiacDetectionView {

    @Bind(R.id.activity_first_change_cardiac_detection_mycardiac_detection_custom_view)
    MyCardiacDetectionCustomView activityFirstChangeCardiacDetectionMycardiacDetectionCustomView;
    @Bind(R.id.activity_first_change_cardiac_detection_ringview)
    RingView activityFirstChangeCardiacDetectionRingview;
    @Bind(R.id.activity_first_change_cardiac_detection_tv_one)
    TextView activityFirstChangeCardiacDetectionTvOne;
    @Bind(R.id.activity_first_change_cardiac_detection_two)
    TextView activityFirstChangeCardiacDetectionTwo;
    @Bind(R.id.activity_first_change_cardiac_detection_tv_three)
    TextView activityFirstChangeCardiacDetectionTvThree;
    @Bind(R.id.activity_first_change_cardiac_detection_tv_heart_rate)
    TextView activityFirstChangeCardiacDetectionTvHeartRate;
    @Bind(R.id.activity_first_change_cardiac_detection_ll_test_date)
    LinearLayout activityFirstChangeCardiacDetectionLlTestDate;
    @Bind(R.id.activity_first_change_cardiac_detection_tv_start)
    TextView activityFirstChangeCardiacDetectionTvStart;
    private MyCardiacDetectionCustomView mycardiac_detection_custom_view;
    private FirstChangeCardiacDetectionPersenter mFirstChangeCardiacDetectionPersenter = new FirstChangeCardiacDetectionPersenter(this);
    private View view;


    private String SERVICES_UUID = "69400001-b5a3-f393-e0a9-e50e24dcca99";
    private String CHARECTERISTIC_UUID = "69400003-b5a3-f393-e0a9-e50e24dcca99";
    private String[] names = new String[1];
    private String devices_name;
    private boolean flag = true;
    private boolean flag_01 = true;
    private RingView ringview;
    private PopupWindow mSearchPopWindow;
    private ImageView iv_error;
    private TextView tv_search_state;
    private ProgressBar progressBar;
    private TextView tv_determine;
    private PopupWindow mDisconnectPopWindow;


    private BleDevice mbleDevice;
    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    private PopupWindow mSearchPopWindow1;
    private PopupWindow mDisconnectPopWindow1;
    private ArrayList<Integer> mlist = new ArrayList<>();
    private boolean Flag_02= false;

    /**
     * @desc 主要内容的布局资源填充进来
     */
    @Override
    protected View setMainContentView() {
        view = View.inflate(this, R.layout.activity_first_change_cardiac_detection, null);
        ButterKnife.bind(this, view);
        return view;
    }

    /**
     * @desc 初始化数据 onCreate()
     */
    @Override
    protected void initView(View view) {
        displayToolbar();
        displayReturn();
        displayTvName();
        displayBtRelease();

        setToolbarBg(0xff2196F3);
        setReturnrePictuResources(R.drawable.backicon);
        setTvNameEachAttribute(20, 0xffffffff, "胎心检测");
        setBtReleaseEachAttribute(18, 0xffffffff, "小贴士", 0x00000000);
        devices_name = getIntent().getStringExtra("devices_name");
        names[0] = "WelBi_"+devices_name;
       // names[0] = "WelBi_0008";
        NLogger.e("TAG","names====================="+names[0]);
        mycardiac_detection_custom_view = (MyCardiacDetectionCustomView) findViewById(R.id.activity_first_change_cardiac_detection_mycardiac_detection_custom_view);
        ringview = (RingView) findViewById(R.id.activity_first_change_cardiac_detection_ringview);
        ringview.startAnim();
        initDate();
    }
    private void initDate() {
        activityFirstChangeCardiacDetectionTvStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mFirstChangeCardiacDetectionPersenter.onClickBtStartTest();
            }
        });

        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setMaxConnectCount(7)
                .setOperateTimeout(5000);
    }
    //todo  /**============================================================**/


    @Override
    public void toTest() {
        checkPermissions(); //todo  开始扫描  ----> 1

    }
    @Override
    public void cancleTest() {
        if(mbleDevice != null){
            if (BleManager.getInstance().isConnected(mbleDevice)) {
                BleManager.getInstance().disconnect(mbleDevice); //TODO 断开连接
            }
        }else{
            BleManager.getInstance().cancelScan();  //todo 2 停止扫描  ----> 2
        }
        ringview.setVisibility(View.GONE);
        mycardiac_detection_custom_view.stopAnim(0.5f);
        SetStartTest(0xffffffff, R.drawable.cardiac_detection_tvbg_selector_nomale,"开始检测");


        mycardiac_detection_custom_view.setFlag(true);
        ringview.setVisibility(View.GONE);
      //  activityFirstChangeCardiacDetectionLlTestDate.setVisibility(View.GONE);
        mycardiac_detection_custom_view.refrsh();
    }


    // todo
    private void setScanRule() {
        // todo 扫描的真正方法  --->5
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setServiceUuids(new UUID[]{UUID.fromString("69400001-b5a3-f393-e0a9-e50e24dcca99")})      // 只扫描指定的服务的设备，可选
                .setDeviceName(true)   // 只扫描指定广播名的设备，可选
                .setAutoConnect(false)      // 连接时的autoConnect参数，可选，默认false
                .setScanTimeOut(2000)              // 扫描超时时间，可选，默认10秒
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
    }
    // todo 扫描的方法
    private void startScan() {
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                //todo 这里  提示进度----> 1
                Flag_02 = true;
                mFirstChangeCardiacDetectionPersenter.search();
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);

            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                NLogger.e("TAG","MyNotify===11====发货单号===========>"+bleDevice.getName());
                if(bleDevice.getName().equals(names[0])){ //WelBi_0008
                    if (!BleManager.getInstance().isConnected(bleDevice)) {  // todo 判断设备是否连接
                        BleManager.getInstance().cancelScan();  //TODO 取消扫描
                        Flag_02 = false;
                        connect(bleDevice);
                    }
                }

            }
            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                if(Flag_02){
                    mFirstChangeCardiacDetectionPersenter.failureSearch();
                  //  activityFirstChangeCardiacDetectionLlTestDate.setVisibility(View.GONE);
                    SetStartTest(0xffffffff, R.drawable.cardiac_detection_tvbg_selector_nomale,"开始检测");
                   // activityFirstChangeCardiacDetectionLlTestDate.setVisibility(View.VISIBLE);
                    ringview.setVisibility(View.GONE);
                    mycardiac_detection_custom_view.stopAnim(0.5f);
                }else{
                    //todo 这里  提示----> 2
                  //  Toast.makeText(FirstChangeCardiacDetectionActivity.this,"设备扫描结束",Toast.LENGTH_SHORT).show();
                }
                Flag_02 = false;
            }
        });
    }
    private void connect(final BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
            }

            @Override
            public void onConnectFail(BleException exception) {  //todo 这里  结束提示进度----> 1
                mFirstChangeCardiacDetectionPersenter.failureSearch();
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                mbleDevice = bleDevice;
                mFirstChangeCardiacDetectionPersenter.connectSuccess();
                getBluetoothGatt(bleDevice, gatt);  //todo 这里  结束提示进度----> 1
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
                if(isActiveDisConnected){
                    Toast.makeText(FirstChangeCardiacDetectionActivity.this,"设备连接断开了",Toast.LENGTH_SHORT).show();
                }else{
                    mFirstChangeCardiacDetectionPersenter.Disconnect();
                    SetStartTest(0xffffffff, R.drawable.cardiac_detection_tvbg_selector_nomale,"开始检测");
                  //  activityFirstChangeCardiacDetectionLlTestDate.setVisibility(View.VISIBLE);
                    ringview.setVisibility(View.GONE);
                    mycardiac_detection_custom_view.stopAnim(0.5f);
                }
            }
        });
    }

    private void getBluetoothGatt(final BleDevice bleDevice, final BluetoothGatt gatt) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //todo 这里 逻辑处理-----获取特征值-------------------------->
                for (BluetoothGattService bluetoothGattService : gatt.getServices()) {
                    if(bluetoothGattService.getUuid().toString().equals("69400001-b5a3-f393-e0a9-e50e24dcca99")){
                        for (BluetoothGattCharacteristic bluetoothGattCharacteristic : bluetoothGattService.getCharacteristics()) {
                            int charaProp =   bluetoothGattCharacteristic.getProperties();
                            if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { // todo 判断是否是  Notify
                                //读取数据
                                MyNotify(bleDevice,bluetoothGattService.getUuid(),bluetoothGattCharacteristic.getUuid());
                            }
                        }
                    }
                }
            }
        }).start();

    }
    private void MyNotify(final BleDevice bleDevice, UUID serviceuuid, UUID Characteristicuuid1) {
        //todo 打开通知
        BleManager.getInstance().notify(bleDevice,
                serviceuuid.toString(),
                Characteristicuuid1.toString(),
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        myController(bleDevice);
                        //todo 这里  停止动画
                    }
                    @Override
                    public void onNotifyFailure(final BleException exception) {}
                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        String str = new String(data);
                     //   NLogger.e("TAG","MyNotify===str====str===========>"+str);
                        if(str.contains("7Ftl_")){  //
                            String[]  srr = str.split("_");
                            if(srr[1].contains("000")){
                                activityFirstChangeCardiacDetectionTvHeartRate.setText("--- bpm");
                                setFetalHeartRateTextone("---",0xff323232);
                            }else{
                                activityFirstChangeCardiacDetectionTvHeartRate.setText(srr[1]+" bpm");
                                mFirstChangeCardiacDetectionPersenter.setFetalHeartRateTex();
                              NLogger.e("TAG","MyNotify===11====发货单号===========>"+srr[1]);
                                //mFirstChangeCardiacDetectionPersenter.TestReSult(srr[1],FirstChangeCardiacDetectionActivity.this);
                            }
                        }else if(str.contains("9StaFt_")) {
                            NLogger.e("TAG","MyNotify=====date==警方内部解决烦恼===========>"+str);
                            String[] srr = str.split("_");
                            mFirstChangeCardiacDetectionPersenter.TestReSult(srr[1].trim(), FirstChangeCardiacDetectionActivity.this);
                            int date  = 0;
                            try {
                                date = Integer.parseInt(srr[1].trim());
                                mlist.add(date);
                            } catch (NumberFormatException e) {

                            }finally {
                                NLogger.e("TAG","MyNotify=====date=============>"+date);

                                /*if(mlist.size()== 4){
                                  int mytestDate =   mlist.get(0)+mlist.get(1)+mlist.get(2)+mlist.get(3);
                                    mFirstChangeCardiacDetectionPersenter.TestReSult(mytestDate/4+"", FirstChangeCardiacDetectionActivity.this);
                                }*/

                            }
                           // NLogger.e("TAG","MyNotify=====22=============>"+srr[1]);
                        }
                    }
                });
    }
    /*==============================**/
    // todo 权限申请----> 3
    private void checkPermissions() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            SetStartTest(0xffffffff, R.drawable.cardiac_detection_tvbg_selector_nomale,"开始检测");
            Toast.makeText(this, "请先打开蓝牙", Toast.LENGTH_LONG).show();
            //activityFirstChangeCardiacDetectionLlTestDate.setVisibility(View.VISIBLE);
            ringview.setVisibility(View.GONE);

            return;
        }
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
                    new AlertDialog.Builder(this)
                            .setTitle("提示")
                            .setMessage("当前手机扫描蓝牙需要打开定位功能")
                            .setNegativeButton("取消",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    })
                            .setPositiveButton("前往设置",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false)
                            .show();
                } else {
                    setScanRule();
                    startScan(); //TODO 开始扫描 扫描的方法  ---->4
                }
                break;
        }
    }


    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_GPS) {
            if (checkGPSIsOpen()) {
                setScanRule();
                startScan();
            }
        }
    }



  //todo  /**============================================================**/
    /**
     * @desc Activity 销毁 释放资源
     */
    @Override
    protected void releaseResources() {
        ButterKnife.unbind(view);
        BleManager.getInstance().disconnectAllDevice(); //todo 释放一些资源
        BleManager.getInstance().destroy();
    }
    /**
     * @desc 网络监听 用于提示用户有网络了
     */
    @Override
    protected void promptHaveInternet() {}
    /**
     * @desc 网络监听 用于提示用户没有网络了
     */
    @Override
    protected void promptNoInternet() {}
    /**
     * @desc 点击分享按钮
     */
    @Override
    protected void onClickShared() {}
    //todo 界面可见  --->1
    @Override
    protected void refreshVariable() {
        super.refreshVariable();
        // flag = true;

    }
    //todo 界面不可见  --->1
    @Override
    protected void solutionRegister() {
        super.solutionRegister();

    }

    /**
     * @desc 点击发布按钮
     */
    @Override
    protected void onClickRelease() {
//        Intent intent = new Intent(FirstChangeCardiacDetectionActivity.this, FirstChangeHistoricalRecordCardiacDetectionActvity.class);
//        startActivity(intent);

        Intent intent = new Intent(FirstChangeCardiacDetectionActivity.this, FirstChangeDirectionsUseActvity.class);
        intent.putExtra("identification_code", 1);
        startActivity(intent);
    }

    /**
     * @desc 点击返回按钮
     */
    @Override
    protected void onClickReturn() {
        finish();
    }


    // todo 显示提示Toast信息
    @Override
    public void showToastInformation(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    //显示测试情况
    @Override
    public void displayRealTimeTestCase() {
        activityFirstChangeCardiacDetectionLlTestDate.setVisibility(View.VISIBLE);
    }

    //隐藏测试情况
    @Override
    public void hiddenRealTimeTestCase() {
        activityFirstChangeCardiacDetectionLlTestDate.setVisibility(View.GONE);
    }

    //获取实时心率
    @Override
    public int getRealTimeHeartRate() {
        String HeartRate = activityFirstChangeCardiacDetectionTvHeartRate.getText().toString().trim();
        String[] arr = HeartRate.split(" ");
        int rate = 0;
        try {
            rate = Integer.parseInt(arr[0]);

        } finally {

            return rate;
        }

    }

    //设置实时心率
    @Override
    public void setRealTimeHeartRate(String str) {
        activityFirstChangeCardiacDetectionTvHeartRate.setText(str);
    }

    //获取胎儿心率  1
    @Override
    public String getFetalHeartRateTextone() {
        return activityFirstChangeCardiacDetectionTvOne.getText().toString().trim();
    }

    //获取胎儿心率  2
    @Override
    public String getFetalHeartRateTextTwo() {
        return activityFirstChangeCardiacDetectionTwo.getText().toString().trim();
    }

    //获取胎儿心率  3
    @Override
    public String getFetalHeartRateTextThread() {
        return activityFirstChangeCardiacDetectionTvThree.getText().toString().trim();
    }

    //设置 胎儿心率 1
    @Override
    public void setFetalHeartRateTextone(String str, int textcolor) {
        activityFirstChangeCardiacDetectionTvOne.setText(str);
        activityFirstChangeCardiacDetectionTvOne.setTextColor(textcolor);
    }

    //设置 胎儿心率 2
    @Override
    public void setFetalHeartRateTextTwo(String str, int textcolor) {
        activityFirstChangeCardiacDetectionTwo.setText(str);
        activityFirstChangeCardiacDetectionTwo.setTextColor(textcolor);
    }

    //设置 胎儿心率 3
    @Override
    public void setFetalHeartRateTextThread(String str, int textcolor) {
        activityFirstChangeCardiacDetectionTvThree.setText(str);
        activityFirstChangeCardiacDetectionTvThree.setTextColor(textcolor);
    }

    //跳转页面
    @Override
    public void toJumpPage() {
        Intent intent = new Intent(FirstChangeCardiacDetectionActivity.this, FirstChangeHistoricalRecordDateListActivity.class);
        startActivity(intent);
    }

    // 获取  开始检测
    @Override
    public String getStartTest() {
        return activityFirstChangeCardiacDetectionTvStart.getText().toString().trim();
    }

    /**
     * 设置开始检测
     *
     * @param textColor 文字颜色
     * @param resId     背景资源
     * @param str       文字内容
     */
    @Override
    public void SetStartTest(int textColor, int resId, String str) {
        activityFirstChangeCardiacDetectionTvStart.setText(str);
        activityFirstChangeCardiacDetectionTvStart.setTextColor(textColor);
        activityFirstChangeCardiacDetectionTvStart.setBackgroundResource(resId);
    }

    //显示蓝牙检测中的提示框
    @Override
    public void showBluetoothTesting() {

    }

    // 显示长时间没有检测到蓝牙的提示框
    @Override
    public void showBluetoothNoTestDate() {

    }

    //显示测试结束的提示框
    @Override
    public void showBluetoothTestOver() {

    }

    //to第二次测试 页面
    @Override
    public void toSecondTimeCardiacDetectionPager() {
        Intent intent = new Intent(FirstChangeCardiacDetectionActivity.this, FrstChangeSecondTimeCardiacDetectionActivity.class);
        startActivity(intent);
    }

    private void myController(final BleDevice bleDevice) {
       mycardiac_detection_custom_view.startAnim(359);
        ringview.setVisibility(View.VISIBLE);

        mycardiac_detection_custom_view.setFlag(false);
        mlist.clear();
       // activityFirstChangeCardiacDetectionLlTestDate.setVisibility(View.VISIBLE);
        mycardiac_detection_custom_view.setmAnimationListener(new MyAnimationListener() {
            @Override
            public void onstart() {

            }

            @Override
            public void onCancel() {
//                ringview.setVisibility(View.GONE);
//                SetStartTest(0xffffffff, R.drawable.cardiac_detection_tvbg_selector_nomale,"开始检测");
//                ringview.stopAnim();
//                activityFirstChangeCardiacDetectionLlTestDate.setVisibility(View.GONE);
            }

            @Override
            public void onRepeat() {

            }

            @Override
            public void onEnd() {
                ringview.setVisibility(View.GONE);
//                ringview.stopAnim();
//                activityFirstChangeCardiacDetectionLlTestDate.setVisibility(View.GONE);
//                mycardiac_detection_custom_view.refrsh();
                activityFirstChangeCardiacDetectionTvHeartRate.setText("--- bpm");
                setFetalHeartRateTextThread("---",0xff323232);
                setFetalHeartRateTextTwo("---",0xff323232);
                setFetalHeartRateTextone("---",0xff323232);
                NLogger.e("TAG","flag=FirstChangeCardiacDetectionActivity==onDraw===============>");
                if (BleManager.getInstance().isConnected(bleDevice)) {
                    BleManager.getInstance().disconnect(bleDevice); //TODO 断开连接
                }
                mycardiac_detection_custom_view.setFlag(true);
                mycardiac_detection_custom_view.stopAnim(0.5f);
                SetStartTest(0xffffffff, R.drawable.cardiac_detection_tvbg_selector_nomale,"开始检测");
            }
        });
    }


    @Override
    public void showSearch() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.blooth_search, null);
        mSearchPopWindow1 = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        mSearchPopWindow1.setContentView(contentView);
        progressBar = contentView.findViewById(R.id.blooth_search_progressBar);
        iv_error = contentView.findViewById(R.id.blooth_search_iv_error);
        tv_search_state = contentView.findViewById(R.id.blooth_search_tv_search_state);
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_first_change_second_time_cariac_detection, null);
        mSearchPopWindow1.showAtLocation(rootview, Gravity.CENTER, 0, 0);
    }

    @Override
    public void cancleSearch() {
        mSearchPopWindow1.dismiss();
    }

    @Override
    public void failureSearch() {
        iv_error.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
        tv_search_state.setText("连接失败");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //mFrstChangeSecondTimeCardiacDetectionPersenter.search();
                //setStartTest("开始测试");
                SetStartTest(0xffffffff, R.drawable.cardiac_detection_tvbg_selector_nomale,"开始测试");
              //  activityFirstChangeCardiacDetectionLlTestDate.setVisibility(View.VISIBLE);
                cancleSearch();
                cancleTest();


            }
        },1000);
    }

    @Override
    public void showDisconnect() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.blooth_disconnect, null);
        mDisconnectPopWindow1 = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        mDisconnectPopWindow1.setContentView(contentView);
        tv_determine = contentView.findViewById(R.id.blooth_disconnect_tv_determine);
        tv_determine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cancleDisconnect();
            }
        });
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_first_change_second_time_cariac_detection, null);
        mDisconnectPopWindow1.showAtLocation(rootview, Gravity.CENTER, 0, 0);
    }

    @Override
    public void cancleDisconnect() {
        mDisconnectPopWindow1.dismiss();
    }

    @Override
    public void connectSuccess() {
        iv_error.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
        tv_search_state.setText("连接成功");
        iv_error.setImageResource(R.mipmap.right_and_wrong);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                SetStartTest(0xff1472FF, R.drawable.cardiac_detection_tvbg_selector_press,"停止");
                cancleSearch();
            }
        },1000);
    }

    @Override
    public void finshPager() {
        finish();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String name = intent.getStringExtra("devices_name_02");
        names[0] = "WelBi_"+name;
    }
}
